﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Nucleic.Core.Utils.WxPay;

namespace Nucleic.Web.Controllers
{
    public class WxPayController : Controller
    {
        public async Task<string> PayH5NotifyUrl()
        {


            //获取回调POST过来的xml数据的代码
            Stream stream = HttpContext.Request.Body;
            byte[] buffer = new byte[HttpContext.Request.ContentLength.Value];
            await stream.ReadAsync(buffer, 0, buffer.Length); //.net core 3.1需要用ReadAsync才不会出错
            string str = System.Text.Encoding.UTF8.GetString(buffer);
            JObject jsonObj = JObject.Parse(str);
            string summary = jsonObj["summary"].ToString();//回调摘要
            if (summary == "支付成功")
            {

                string associatedData = ((JObject)jsonObj["resource"])["associated_data"].ToString();//附加数据
                string nonce = ((JObject)jsonObj["resource"])["nonce"].ToString();//随机串
                string ciphertext = ((JObject)jsonObj["resource"])["ciphertext"].ToString();//数据密文
                //调用解密
                var decryptStr = AesGcm.AesGcmDecrypt(associatedData, nonce, ciphertext);
                JObject resource = JObject.Parse(decryptStr);
                string attach = resource["attach"].ToString();//附加数据
                string out_trade_no = resource["out_trade_no"].ToString();//商户订单号
                string transaction_id = resource["transaction_id"].ToString();//信支付订单号
                string total_fee = ((JObject)resource["amount"])["total"].ToString();//总金额
                string return_code = resource["trade_state"].ToString();//交易状态

                try
                {
                    //业务逻辑
                    if (return_code.ToUpper() == "SUCCESS")
                    {
                        return "{"
                        + "\"code\":\"SUCCESS\","
                        + "\"message\":\"成功\","
                        + "}";
                    }
                }
                catch (Exception e)
                {
                    throw;
                }
            }
            return "{"
                         + "\"code\":\"FAIL\","
                         + "\"message\":\"ERROR\","
                         + "}";

        }
        public IActionResult Index()
        {
            return View();
        }
    }
}
